# Script to create a new Visual studio solution based on Injasuti.Samples.SP2007.Template

# .\Create-Solution.ps1 "IC-Main" "Main" true "Create-Solution.xml"
# .\Create-Solution.ps1 "IC-Main-CSOM" "Main-CSOM" true "Create-Solution.xml"


# Expects the following parameters
# =====
#   source folder
#   destination folder
#   overwrite flag
#   configuration file name
# TODO: Validate parameters

param([string]$sourceFolder, [string]$destinationFolder, [string]$overwrite, [string]$configFileName)

CLS

# Set global parameters
# =====

$ErrorActionPreference = "Stop"
#$configXml = [xml] "<Configuration name='Developer' version='1.0'></Configuration>"
$restartServices = "False"
$processStartDateTimeString = Get-Date -format "yyyyMMdd-HHmmss"

# Functions
# =====

function TXT-ChangeText([string] $inputFileName, [string]$outputFileName, [string]$searchFor, [string]$replaceWith, [string]$format)
{
	if ([System.String]::IsNullOrEmpty($format) -eq $FALSE)
	{
    $command = "c:\Install\Injasuti\Injasuti.Consulting.Console.Utilities.exe -o replaceinfile -s `"$inputFileName`" -t `"$outputFileName`" -f `"$searchFor`" -r `"$replaceWith`" -a `"$format`"" 
	}
	else
	{
    $command = "c:\Install\Injasuti\Injasuti.Consulting.Console.Utilities.exe -o replaceinfile -s `"$inputFileName`" -t `"$outputFileName`" -f `"$searchFor`" -r `"$replaceWith`"" 
	}
  Write-Host $command
  Invoke-Expression "$command"
}

function Do-Renames([System.Xml.XmlElement]$configXml, [string]$rootPath)
{
  Write-Host "Processing" $rootPath
  
  # Rename folders
	if ($configXml.Renames.Folders)
	{
	  $x = (Get-ChildItem $rootPath | Where-Object {$_.PSIsContainer -eq $True}) | Where-Object {$_.FullName.Length -gt 0} | Select-Object $_
	  foreach ($d in $x)
	  {
	    $y = $d.FullName
	    if ([System.String]::IsNullOrEmpty($y) -eq $FALSE)
	    {
	      $originalFolder = $d.FullName.Substring($rootPath.Length)
	      $fullOriginalFolder = $rootPath + $originalFolder
	      #Write-Host "Found folder " $originalFolder

	      foreach ($folderRename in $configXml.Renames.Folders.Rename)
	      {
	        if ($originalFolder.IndexOf($folderRename.Name) -ge 0)
	        {
	          $renamedFolder      = $originalFolder.Replace($folderRename.Name, $folderRename.Value)
	          $fullRenamedFolder  = $rootPath + $renamedFolder
	          write-host "renaming folders  : '" $fullOriginalFolder "' to '" $fullRenamedFolder "'"
	          Move-Item $fullOriginalFolder $fullRenamedFolder -force
	          $originalFolder     = $renamedFolder
	          $fullOriginalFolder = $fullRenamedFolder
	        }
	      }

	      Do-Renames $configXml $fullOriginalFolder
	    }
	  }
	}
	
  # Rename files
	if ($configXml.Renames.Files)
	{
    $x = (Get-ChildItem $rootPath -recurse -force | Where-Object {$_.PSIsContainer -eq $False}) | Where-Object {$_.FullName.Length -gt 0} | Select-Object $_
    foreach ($d in $x)
    {
      $y = $d.FullName
      if ([System.String]::IsNullOrEmpty($y) -eq $FALSE)
      {
        $originalFile = $d.FullName.Substring($rootPath.Length)
        $fullOriginalFile = $rootPath + $originalFile
        #Write-Host "Found file " $fullOriginalFile
        
    		foreach ($fileRename in $configXml.Renames.Files.Rename)
    		{
    		  if ($originalFile.IndexOf($fileRename.Name) -ge 0)
    		  {
				    $renamedFile      = $originalFile.Replace($fileRename.Name, $fileRename.Value)
				    $fullRenamedFile  = $rootPath + $renamedFile
				    write-host "renaming file  : '" $fullOriginalFile "' to '" $fullRenamedFile "'"
				    Move-Item $fullOriginalFile $fullRenamedFile -force
    		  }
    		}
      }
    }
	}
}

function Do-Replacements([System.Xml.XmlElement]$configXml, [string]$rootPath)
{
	if ($configXml.Replaces.Content)
	{
		foreach ($contentReplace in $configXml.Replaces.Content.Replace)
		{
		  $targetPath = $($rootPath + "\" + $contentReplace.Path + "\*").Replace("\\", "\")
      $targetPath
      if ((Test-Path -path $targetPath) -eq $True)
      {
        Write-Host "Checking path" $targetPath "for files" $contentReplace.FileMask
        # $x = (Get-ChildItem $targetPath -recurse -force -include $mask | Where-Object {$_.PSIsContainer -eq $False}) | Where-Object {$_.FullName.Length -gt 0} | Select-Object $_
        # n.b. using invoke expression because filemask of "*.cs,*.xml" produces no results when run "directly".
        $command = "Get-ChildItem " + $targetPath + " -recurse -force -include " + $contentReplace.FileMask
        $y = Invoke-Expression "$command"
        $x = $y | Where-Object {$_.PSIsContainer -eq $False}
        foreach ($d in $x)
        {
          $y = $d.FullName
          if ([System.String]::IsNullOrEmpty($y) -eq $FALSE)
          {
            $originalFile = $d.FullName.Substring($rootPath.Length)
            $fullOriginalFile = $rootPath + $originalFile
		        Write-Host "replacing content : '" $contentReplace.SearchFor "' to '" $contentReplace.ReplaceWith "' in file '" $fullOriginalFile "' with format '" $contentReplace.Format "'" 
		        TXT-ChangeText $fullOriginalFile $fullOriginalFile $contentReplace.SearchFor $contentReplace.ReplaceWith $contentReplace.Format
          }
        }
      }
		}
	}
}

function Create-Folder ([string]$folderName, [string]$deleteExisting)
{
  #Create subfolder for the backups
  if ($deleteExisting -imatch "true")
  {
    if ((Test-Path -path $folderName) -eq $True)
    {
    	Write-Host "Deleting  : " $folderName -ForegroundColor DarkCyan -BackgroundColor White
    	Remove-Item $folderName -recurse -force
    }
  }
  if ((Test-Path -path $folderName) -ne $True)
  {
  	Write-Host "Creating  : " $folderName -ForegroundColor DarkCyan -BackgroundColor White
  	New-Item $folderName -type directory
  }
}

function Copy-Source([string]$targetFolder, [string]$sourceFolder)
{
  xcopy $sourceFolder\*.* $targetFolder /E /D /C /F /H /R /K /Y /V
}

# Main
# =====

#Start-Transcript -path .\CreateSolution.Results.doc -force 

Write-Host 
Write-Host $sourceFolder             -BackgroundColor Blue -ForegroundColor Yellow
Write-Host $destinationFolder        -BackgroundColor Blue -ForegroundColor Yellow
Write-Host $overwrite                -BackgroundColor Blue -ForegroundColor Yellow
Write-Host $configFileName           -BackgroundColor Blue -ForegroundColor Yellow
Write-Host 
Write-Host $action " - STARTED" $([System.DateTime]::Now).ToString()	-BackgroundColor Blue -ForegroundColor Yellow
Write-Host 

# Check input parameters

[string] $targetConfigFileName = Get-Location
$targetConfigFileName = $targetConfigFileName + "\" + $configFileName
$targetConfigFileName = $targetConfigFileName -replace "\\.\\", "\"

# Check that the config file exists.
if (-not $(Test-Path -Path $targetConfigFileName -Type Leaf))
{
	Write-Error -message ("Configuration file '" + $configFileName + "' does not exist.")
}
Write-Host $targetConfigFileName       -BackgroundColor Blue -ForegroundColor Yellow
# TODO: Validate the config file against an XSD.

$configXml = [xml]$(get-content $configFileName)
if ($configXml.Configuration.Properties.Verbosity -eq "DIAG")
{
	type $configFileName
}

# Check destination folder

[string] $targetDestinationFolder = Get-Location
$targetDestinationFolder = $targetDestinationFolder + "\" + $destinationFolder
$targetDestinationFolder = $targetDestinationFolder -replace "\\.\\", "\"
Write-Host $targetDestinationFolder       -BackgroundColor Blue -ForegroundColor Yellow

# Do some work

Create-Folder                            $targetDestinationFolder "true"
Copy-Source                              $targetDestinationFolder $sourceFolder
attrib -r $targetDestinationFolder\*.* /S
Do-Renames      $configXml.Configuration $targetDestinationFolder
Do-Replacements $configXml.Configuration $targetDestinationFolder

#throw "Stopping now"

Write-Host 
Write-Host $action " - ENDED" $([System.DateTime]::Now).ToString()	-BackgroundColor Blue -ForegroundColor Yellow
Write-Host 

#Stop-Transcript
